
import chatLogic
from whiff.middleware import misc
from whiff import resolver
from whiff import whiffenv

class LogoutAction(misc.utility):
    def __init__(self, page):
        self.page = page
    def __call__(self, env, start_response):
        my_start_response = start_response
        nick = chatLogic.getCookieValue(env)
        variable = whiffenv.getName(env, ".nick")
        envcopy = env.copy()
        # delete the nick from the environment
        #pr "deleting var", repr(variable)
        try:
            del envcopy[variable]
        except KeyError:
            # ignore absent entry ?
            #pr "delete failed"
            pass
        # remove the nick from the database
        if nick is not None:
            #pr "removing nick from database", repr(nick)
            #connection = chatLogic.test_gadfly_connection(whiffenv.getId(env, "DbPrefix"))
            connection = chatLogic.getConnection(env)
            connection.removeSpeaker(nick)
            connection.commit()
            # also unset the cookie
            def my_start_response(status, headers):
                my_headers = headers[:]
                cookieName = chatLogic.cookieName(env)
                nickname = "X"
                cookietext = "%s=%s; path=/" % (cookieName, nickname)
                #pr "setting cookie", repr(cookietext)
                my_headers.append( ('Set-Cookie', str(cookietext)) )
                #pr "sending headers", my_headers
                start_response(status, my_headers)
        return self.deliver_page(self.page, envcopy, my_start_response)

__middleware__ = LogoutAction

